<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="../static/js/config/jquery-3.3.1.min.js"></script>
    <link rel="stylesheet" href="https://a.amap.com/jsapi_demos/static/demo-center/css/demo-center.css" />
    <script type="text/javascript">
        window._AMapSecurityConfig = {
            securityJsCode: '你的密钥',  //密钥
        }
    </script>
    <script type="text/javascript"
        src="https://webapi.amap.com/maps?v=1.4.15&key=你的key&plugin=AMap.DistrictSearch"></script>
    <script src="https://webapi.amap.com/loader.js"></script>
</head>
<style>
    html,
    body,
    #container {
        margin: 0;
        height: 100%;
        width: 100%
    }

    .input-item-text {
        width: 7rem;
    }

    .content-window-card {
        position: relative;
        box-shadow: none;
        bottom: 0;
        left: 0;
        width: auto;
        padding: 0;
    }

    .content-window-card p {
        height: 2rem;
    }

    .custom-info {
        border: solid 1px silver;
    }

    div.info-top {
        position: relative;
        background: none repeat scroll 0 0 #F9F9F9;
        border-bottom: 1px solid #CCC;
        border-radius: 5px 5px 0 0;
    }

    div.info-top div {
        display: inline-block;
        color: #333333;
        font-size: 14px;
        font-weight: bold;
        line-height: 31px;
        padding: 0 10px;
    }

    div.info-top img {
        position: absolute;
        top: 10px;
        right: 10px;
        transition-duration: 0.25s;
    }

    div.info-top img:hover {
        box-shadow: 0px 0px 5px #000;
    }

    div.info-middle {
        font-size: 12px;
        padding: 10px 6px;
        line-height: 20px;
    }

    div.info-bottom {
        height: 0px;
        width: 100%;
        clear: both;
        text-align: center;
    }

    div.info-bottom img {
        position: relative;
        z-index: 104;
    }

    span {
        margin-left: 5px;
        font-size: 11px;
    }

    .info-middle img {
        float: left;
        margin-right: 6px;
    }



    .collision-btn.disable {
        background-image: none;
        color: lightgrey;
        border-color: lightgrey;
        cursor: not-allowed;
    }

    .collision-btn.disable:hover {
        background-color: #fff;
        border-color: lightgrey;
    }

    .input-card .btn {
        margin-right: .8rem;
    }
</style>

<body>
    <div id="container"></div>
    <div class="info">
        各个省市中高风险地区分布点
    </div>
    <div class="input-card">
        <label style='color:grey'>行政区边界查询</label>

        <div class="input-item">
            <div class="input-item-prepend">
                <span class="input-item-text">名称/adcode</span>
            </div>
            <input id='district' type="text" value="朝阳">

        </div>


        <label style="color:grey">地图图标注避让设置</label>
        <div class="input-item">
            <input id="allowCollision" type="button" class="btn collision-btn" onclick="allowCollisionFunc()"
                value="标注避让Marker">
            <input id="notAllowCollision" type="button" class="btn collision-btn" onclick="notAllowCollisionFunc()"
                value="标注不避让Marker">
        </div>

    </div>






</body>

<script type="text/javascript">


    // 初始化地图对象，加载地图
    var map = new AMap.Map('container', {
        pitch: 0, // 地图俯仰角度，有效范围 0 度- 83 度
        viewMode: '3D', // 地图模式
        terrain: true // 开启地形图
    });

    map.plugin(["AMap.OverView"], function () {
        map.addControl(new AMap.OverView()); //鹰眼插件；在地图右下角显示地图的缩略图
    });
    map.plugin(["AMap.MapType"], function () {
        map.addControl(new AMap.MapType()); //实现默认图层与卫星图、实施交通图层之间切换的控件
    });
    map.plugin(["AMap.ToolBar"], function () {
        map.addControl(new AMap.ToolBar()); // 工具条控件;范围选择控件
    });
    map.plugin(["AMap.Scale"], function () {
        map.addControl(new AMap.Scale()); // 比例尺条控件
    });


    //由于部分平台省份城市名字后面有市，区
    function likename(str1, str2) {

        if (str1 == null || str2 == null) {
            return false;
        }
        for (var i = 0; i <= str1.length - 1; i++) {

            if (str1.substr(i, 1) == "湖" || str1.substr(i, 1) == "河" || str1.substr(i, 1) == "西" || str1.substr(i, 1) == "阿" || str1.substr(i, 1) == "区" || str1.substr(i, 1) == "市" || str1.substr(i, 1) == "州" || str1.substr(i, 1) == "地") {
                if (i != str1.length - 1) {
                    continue
                } else {
                    return false;
                }

            }

            if (str2.indexOf(str1.substr(i, 1)) != -1) {

                return true;
            }
            else if (i == str1.length - 1) {

                return false;
            }


        }

    }




    window.addEventListener('message', function (e) {

        $.ajax({
            type: "GET",
            url: "/getlnglat",
            data: {
                'address': e.data.area
            },
            async: false,
            success: function (data) {
                var fxaddress = data.data
                drawBounds(e.data.area)
                fxsd(e.data.area, fxaddress)
            }
        })

        $('#district').attr('value', e.data.area)

        console.log(e.data.area)


    })








    var polygons = [];
    var markers = [];
    var allowCollision = true;
    var layer = new AMap.LabelsLayer({
        // zooms: [3, 20],
        zIndex: 1000,
        // collision: false,
        // 设置 allowCollision：true，可以让标注避让用户的标注
        collision: allowCollision,
    });

    var iconRed = {
        // 图标类型，现阶段只支持 image 类型
        type: 'image',
        // 图片 url
        image: '../static/images/bingdu1.png',
        // 图片尺寸
        size: [30, 40],
        // 图片相对 position 的锚点，默认为 bottom-center
        anchor: 'center',
    };

    var iconDefault = {
        // 图标类型，现阶段只支持 image 类型
        type: 'image',
        // 图片 url
        image: '../static/images/bingdu2.png',
        // 图片尺寸
        size: [30, 40],
        // 图片相对 position 的锚点，默认为 bottom-center
        anchor: 'center',
    };

    var textStyle = {
        fontSize: 15,
        fontWeight: 'normal',
        fillColor: '#000000',
        strokeColor: '#fff',
        strokeWidth: 2,
        fold: true,
        padding: '2, 5',
    };


    layer.add(markers);
    // 图层添加到地图
    map.add(layer);



    //封装一个接收后端数据转化为前端固定格式数据的方法
    function changeToDt(arr, value, r, f) {

        var arrData = []

        for (var i = 0; i < arr.length; i++) {

            var flag = likename(arr[i].city, value)

            if (flag) {
                if (arr[i].type === "高风险") {
                    var point =
                    {
                        'name': "高风险",
                        'position': arr[i].location,
                        'opacity': 1,
                        'zIndex': 4,
                        'icon': r,
                        'extData': arr[i].datetime,
                        'text': {
                            'content': arr[i].county + arr[i].address,
                            'direction': 'right',
                            'offset': [-5, -5],
                            'style': textStyle
                        }

                    }

                }
                if (arr[i].type === "中风险") {
                    var point =
                    {
                        'name': "中风险",
                        'position': arr[i].location,
                        'opacity': 1,
                        'zIndex': 4,
                        'icon': f,
                        'extData': arr[i].datetime,
                        'text': {
                            'content': arr[i].county + arr[i].address,
                            'direction': 'right',
                            'offset': [-5, -5],
                            'style': textStyle
                        }
                    }
                }

                arrData.push(point);

            }

        }

        return arrData

    }





    var LabelsData = []
    var polygon;

    function fxsd(addresvalue, dt){
        layer.remove(markers)//清除上次结果
        LabelsData = []
        markers = []

        var LabelsData = changeToDt(dt, addresvalue, iconRed, iconDefault)

        for (var i = 0; i < LabelsData.length; i++) {
            var curData = LabelsData[i];
            var labelMarker = new AMap.LabelMarker(curData);
            markers.push(labelMarker);
            labelMarker.on('click', function (e) {
                console.log("e:")
                console.log(e)
                //实例化信息窗体
                console.log(e.target.De.extData)
                var type = e.target.De.name
                var text = e.target.De.text.content
                var update_time = e.target.De.extData
                var title = title = '风险地区:<sqpan style="font-size:11px;color:#F00;">' + type + '</span>'
                if (type === "高风险") {
                    title = '风险地区:<sqpan style="font-size:11px;color:#F00;">' + type + '</span>'
                }
                if (type === "中风险") {
                    title = '风险地区:<sqpan style="font-size:11px;color:#FFA500;">' + type + '</span>'
                }

                content = [];
                content.push("地址:" + text + "")
                content.push("疫情信息更新时间：" + update_time + "");
                var infoWindow = new AMap.InfoWindow({
                    isCustom: true,  //使用自定义窗体
                    content: createInfoWindow(title, content.join("<br/>")),
                    offset: new AMap.Pixel(16, -45)
                });
                console.log(e)
                console.log(e.target.De.text.content)
                infoWindow.open(map, e.data.data.position)
            });

        }

        layer.add(markers); //再加点
    }


    function drawBounds(addresvalue) {
        console.log("1:"+addresvalue)

        var opts = {
            subdistrict: 0,   //获取边界不需要返回下级行政区
            extensions: 'all',  //返回行政区边界坐标组等具体信息
            level: 'district'  //查询行政级别为 市
        };

        district = new AMap.DistrictSearch(opts);
        console.log("2:"+addresvalue)
        straddres = addresvalue.trim();
        console.log(straddres)
        district.search(straddres, function(status, result) {
            console.log("3:"+addresvalue)
            console.log(result)
            if(polygon){
              map.remove(polygon)//清除上次结果
          	  polygon  = null;
            }
            var bounds = result.districtList[0].boundaries;
            if (bounds) {
              //生成行政区划polygon
              for(var i=0;i<bounds.length;i+=1){//构造MultiPolygon的path
                bounds[i] = [bounds[i]]
              }
              polygon = new AMap.Polygon({
                strokeWeight: 1,
                path: bounds,
                fillOpacity: 0.4,
                fillColor: '#80d8ff',
                strokeColor: '#0091ea'
              });
              map.add(polygon)
              map.setFitView(polygon);//视口自适应
            }
        });


        // AMap.plugin('AMap.DistrictSearch', function () {
        //     // 创建行政区查询对象
        //     var district = new AMap.DistrictSearch({
        //     // 返回行政区边界坐标等具体信息
        //     extensions: 'all',
        //     // 设置查询行政区级别为 市
        //     // level: 'city'
        //     level: 'district'  //查询行政级别为 市
        //   })

        //   district.search(value, function(status, result) {
        //     $("#level ").val(result.districtList[0].level);
        //     console.log(status)
        //     console.log(result)
        //     // 获取边界信息
        //     var bounds = result.districtList[0].boundaries
        //     map.remove(polygons)//清除上次结果
        //     polygons = []
        //     if (bounds) {
        //       for (var i = 0, l = bounds.length; i < l; i++) {
        //        //生成行政区划polygon
        //        var polygon = new AMap.Polygon({
        //          map: map,
        //          strokeWeight: 2,
        //          path: bounds[i],
        //          fillOpacity: 0.3,
        //          fillColor: '#CCF3FF',
        //          strokeColor: '#CC66CC'
        //        });
        //        polygons.push(polygon)
        //      }
        //      map.add(polygons)
        //      // 地图自适应
        //      map.setFitView()
        //    }
        //  })
        // })

    }

    // //点击查询跳转到当前行政区
    // function findCity(){
    //     console.log('点击查询')
    //     var fCity = document.getElementById('district').value
    //     drawBounds(fCity)
    // }


    //构建自定义信息窗体
    function createInfoWindow(title, content) {
        var info = document.createElement("div");
        info.className = "custom-info input-card content-window-card";

        //可以通过下面的方式修改自定义窗体的宽高
        info.style.width = "400px";
        // 定义顶部标题
        var top = document.createElement("div");
        var titleD = document.createElement("div");
        var closeX = document.createElement("img");
        top.className = "info-top";
        titleD.innerHTML = title;
        closeX.src = "https://webapi.amap.com/images/close2.gif";
        closeX.onclick = closeInfoWindow;

        top.appendChild(titleD);
        top.appendChild(closeX);
        info.appendChild(top);

        // 定义中部内容
        var middle = document.createElement("div");
        middle.className = "info-middle";
        middle.style.backgroundColor = 'white';
        middle.innerHTML = content;
        info.appendChild(middle);

        // 定义底部内容
        var bottom = document.createElement("div");
        bottom.className = "info-bottom";
        bottom.style.position = 'relative';
        bottom.style.top = '0px';
        bottom.style.margin = '0 auto';
        var sharp = document.createElement("img");
        sharp.src = "https://webapi.amap.com/images/sharp.png";
        bottom.appendChild(sharp);
        info.appendChild(bottom);
        return info;
    }

    //关闭标记信息窗体
    function closeInfoWindow() {
        map.clearInfoWindow();
    }

    toggleBtn();

    function allowCollisionFunc() {
        allowCollision = true;
        layer.setCollision(true);
        toggleBtn();
    }

    function notAllowCollisionFunc() {
        allowCollision = false;
        layer.setCollision(false);
        toggleBtn();
    }

    function toggleBtn() {
        var allowCollisionBtn = document.getElementById('allowCollision');
        var notAllowCollisionBtn = document.getElementById('notAllowCollision');
        var disableClass = 'disable';

        if (allowCollision) {
            allowCollisionBtn.classList.add(disableClass);
            notAllowCollisionBtn.classList.remove(disableClass);
        } else {
            allowCollisionBtn.classList.remove(disableClass);
            notAllowCollisionBtn.classList.add(disableClass);
        }
    }


</script>

</html>